package com.yeskery.nut.web.demo.config;

import com.alibaba.fastjson2.JSON;
import com.yeskery.nut.annotation.aop.*;
import com.yeskery.nut.aop.Execution;
import com.yeskery.nut.aop.Invocation;
import com.yeskery.nut.util.StringUtils;
import com.yeskery.nut.web.demo.common.Log;

import java.lang.reflect.Method;
import java.util.logging.Logger;

/**
 * 切面配置类
 * @author Yeskery
 * 2023/8/9
 */
@Aspect
public class AspectConfig {

    /** 日志对象 */
    private static final Logger logger = Logger.getLogger(AspectConfig.class.getName());

    @Pointcut("@annotation(com.yeskery.nut.web.demo.common.Log)")
    public void logPointcut() {
    }

    @Around("logPointcut()")
    public void aroundLogPointcut(Invocation invocation) {
        Method originalMethod = invocation.getExecutionMetadata().getMethod();
        Log log = originalMethod.getAnnotation(Log.class);
        String logType = StringUtils.isEmpty(log.value()) ? "默认" : log.value();
        logger.info("日志记录开始，日志类型:" + logType + "，入参:" + JSON.toJSONString(invocation.getExecutionMetadata().getMethodParameters()));
        Object result = invocation.invoke();
        logger.info("日志记录结束，日志类型:" + logType + "，响应结果" + (result == null ? "为空" : ":" + JSON.toJSONString(result)));
    }

    @Pointcut("execution(public void com.yeskery.nut.web.demo.biz.LogBiz.logByDefault(java.lang.String))")
    public void logMethodPointcut() {
    }

    @Before("logMethodPointcut()")
    public void beforeLogMethodPointcut(Execution execution) {
        logger.info("日志方法记录Before切面开始，日志内容:" + execution.getExecutionMetadata().getMethodParameters()[0]);
    }

    @After("logMethodPointcut()")
    public void afterLogMethodPointcut(Execution execution) {
        logger.info("日志方法记录After切面开始，日志内容:" + execution.getExecutionMetadata().getMethodParameters()[0]);
    }
}
